import sys
import find_new_traffic as fnt
import max_min_fairness as mmf
import threshold_TE as tt
import numpy as np
import pandas as pd
sys.path.append("../traffic")
sys.path.append("../config")
import read_traffic as rt
import run_config as rc


def ToE_TE(traffic_seq, pod_num, a_link_bandwidth, link_num):
    bandwidth_upper_bound = a_link_bandwidth * link_num
    new_traffic, S, virtual_r_array = fnt.get_new_traffic(traffic_seq, True, bandwidth_upper_bound)
    topo = mmf.Topology()
    topo = topo.topology([new_traffic], pod_num, a_link_bandwidth, link_num)
    
    # TODO: modify topo in Mininet
    shape = topo.shape
    bandwidth = np.zeros(shape)
    for i in range(shape[0]):
        for j in range(shape[1]):
            bandwidth[i][j] = topo[i][j] * 3 / sum(topo[i])
    bandwidth = bandwidth.reshape(1, shape[0] * shape[1])
    pd.DataFrame(bandwidth).to_csv(f'../traffic/{pod_num}pod_topo.csv', header = False, index = False)

    ret = tt.Routing(topo)
    threshold = ret.routing(S, virtual_r_array, a_link_bandwidth, link_num)
    
    return threshold, virtual_r_array


def create_threshold_file(traffic_arr, pod_num, a_link_bandwidth, link_num):
    traffic_seq = traffic_arr[0:4]
    threshold, virtual_r_array = ToE_TE(traffic_seq, pod_num, a_link_bandwidth, link_num)
    threshold = threshold.reshape(1, pod_num * pod_num).astype(int)
    
    res_virtual_r = pd.DataFrame(virtual_r_array.reshape(1, pod_num))
    res_virtual_r.to_csv(f'../traffic/{pod_num}pod_virtual_r.csv', header = False, index = False)

    res_threshold = pd.DataFrame(threshold)
    res_threshold.to_csv(f'../traffic/{pod_num}pod_threshold.csv', header = False, index = False)

    # with open(f'../traffic/{pod_num}pod_threshold.csv') as f:
        # f.write()

    # TODO: 可以把所有流量都跑完，每次传给ToE_TE一组流量，算出每一行结果输出到 traffic

    # TODO: 结果输出到的 traffic 的 {pod_num}pod_threshold.csv 和 {pod_num}pod_virtual_r.csv 文件
    


if __name__ == "__main__":
    pod_num = rc.pod_num
    a_link_bandwidth = rc.a_link_bandwidth
    link_num = rc.link_num

    traffic_file = '../traffic/' + str(pod_num) + 'pod_traffic.csv'
    traffic_arr = rt.get_traffic(traffic_file)
    create_threshold_file(traffic_arr, pod_num, a_link_bandwidth, link_num)
